<template>
    <div id="homePage">
		<div class="left-section">
			<a-space direction="vertical" size="large" class="filter-space" fill>
				<a-card :bordered="false" class="filter-card">
					<a-space size="middle" wrap>
						<a-input v-model="questionName" placeholder="输入题目名称进行搜索" style="width: 200px" allow-clear />

						<a-select v-model="questionTag" placeholder="选择题目标签" style="width: 200px" allow-clear>
							<a-option value="简单">简单</a-option>
							<a-option value="中等">中等</a-option>
							<a-option value="困难">困难</a-option>
						</a-select>

						<a-select v-model="questionStatus" placeholder="状态" style="width: 200px" allow-clear>
							<a-option value=2>已完成</a-option>
							<a-option value=3>未完成</a-option>
						</a-select>
				
						<a-switch v-model="alignLeft" />
						<span>启用筛选</span>
					</a-space>
				</a-card>
				<a-table
				    :columns="columns"
				    :data="filterList"
				    :pagination="{
				        showTotal: true,
				        total,
				        current: page.current,
				        pageSize: page.pageSize,
				    }"
				    @page-change="pageChange"
				>
					<template #status="{ record }">
						<icon-check />
						<div v-if="record.status == 2">
							<a-space size="large">
							    <icon-check-circle :style="{fontSize:'32px', color: 'green'}" />
							</a-space>
						</div>
					</template>
				    <template #tags="{ record }">
				        <a-space wrap>
				            <a-tag
				                v-for="(tag, index) of record.tags"
				                :key="index"
				                color="green"
				            >
				                {{ tag }}</a-tag
				            >
				        </a-space>
				    </template>
				    <template #acceptedRate="{ record }">
				        <a-space>
				            {{
				                `${
				                    record.submitNum
				                        ? (record.acceptedNum * 100 / record.submitNum).toFixed(2)
				                        : "0"
				                }%(${record.acceptedNum}/${record.submitNum})`
				            }}
				        </a-space>
				    </template>
				    <template #optional="{ record }">
				        <a-space>
				            <a-button status="success" @click="toQuestionPage(record)"
				                >做题</a-button
				            >
				        </a-space>
				    </template>
				</a-table>
			</a-space>
		</div>
		<a-space class="right-section" direction="vertical">
			 <a-date-picker
			      default-value="2019-06-03"
			      v-model:pickerValue="pickerValue"
			      hide-trigger
			      style="width: 268px;margin-top: 100px;"
			    />
			<span id="mainChart" style="width: 266px;height: 200px;flex: ;"></span>
		</a-space>
		
	</div>
    
</template>

<script setup lang="ts">
import { BaseResponse_QuestionWithSubmit } from "../generated/models/BaseResponse_QuestionWithSubmit";
import { computed, onMounted, onUnmounted, ref, watch, watchEffect } from "vue";
import {
    Question,
    QuestionControllerService,
    QuestionQueryRequest,
} from "../generated";
import message from "@arco-design/web-vue/es/message";
import { nextTick } from 'vue'; // 导入 nextTick
import { useRouter } from "vue-router";
import moment from "moment";
import { List } from "ant-design-vue";
import { IconPlus, IconCheckCircle } from '@arco-design/web-vue/es/icon';
import { boolean } from "effect/FastCheck";
import { useStore } from "vuex";
import { QuestionWithSubmit } from "generated/models/QuestionWithSubmit";
import { number } from "effect/Equivalence";
import * as echarts from 'echarts';
type EChartsOption = echarts.EChartsOption;
let myChart: echarts.ECharts | null = null; 
let option: EChartsOption;
const router = useRouter();
const pickerValue = null;
const show = ref(true);
const alignLeft = ref(false);
const questionName = ref('');
const questionTag = ref('');
const questionStatus = ref();
const dataList = ref<QuestionWithSubmit[]>([]);
const originDataList = ref<QuestionWithSubmit[]>([]);
const userFinishedList = ref<QuestionWithSubmit[]>([]);
const onPanelChange = (value: any, mode: any) => {
  console.log(value, mode);
};
const value = ref(new Date('2025-01-01'));
const resetFilters = () => {
		questionName.value = '';
		questionTag.value = '';
		questionStatus.value = '';
	};
const page = ref<QuestionQueryRequest>({
    title: "",
    tags: [],
    pageSize: 10,
    current: 1,
});
const store = useStore();
//先执行page.value然后再执行...展开运算符
const pageChange = (num: number) => {
    page.value = {
        ...page.value,
        current: num,
    };
};
const toQuestionPage = (record: Question) => {
    router.push({
        path: `/view/question/${record.id}`,
        params: { id: record.id },
    });
};
let total = computed(() => filterList.value.length);
const filterList = computed(()=>{
	return originDataList.value.filter((item : QuestionWithSubmit) =>{
		if (!questionTag.value && !questionName.value && !questionStatus.value) {
		      return true; 
		    }
		    const matchTag = !questionTag.value 
		      ? true 
		      : (item?.tags?.length ? item.tags.includes(questionTag.value) : false);

		    const matchName = !questionName.value 
		      ? true 
		      : (item?.title ? item.title.includes(questionName.value) : false);

		    const matchStatus = questionStatus.value === undefined || questionStatus.value === null 
		      ? true 
		      : (item?.status !== undefined && Number(item.status) == questionStatus.value);
		return matchTag && matchName && matchStatus;
	})
});
const loadData = async () => {
	let userId =store.state.user?.loginUser?.id;
	console.log("userId",userId)
	if(userId != "" && userId != null){
		let res = await QuestionControllerService.listQuestionWithSubmit(
		 String(userId),"1973742216766410753"
		)as unknown as BaseResponse_QuestionWithSubmit;
		console.log(res);
		console.log("9999999999999")
		if (res.code === 0) {
			originDataList.value = res.data ?? [];
		    dataList.value = res.data ?? [];
			userFinishedList.value = dataList.value.filter(item => item.status == 2);
			console.log("dataList",dataList)
			// 执行图表初始化
			initChart();
		} else {
		    message.error("加载失败" + res.message);
		}
	}
    
};
// 初始化图表
	  const initChart = () => {
	    // 先销毁可能存在的旧实例（避免重复初始化）
	    if (myChart) {
	      myChart.dispose();
	    }
	    // 获取 DOM 元素（此时模板已渲染，可正确获取）
	    const chartDom = document.getElementById('mainChart');
	    if (!chartDom) { // 校验：确保 DOM 存在
	      console.error('未找到 ID 为 mainChart 的元素');
	      return;
	    }
	    // 初始化 ECharts 实例
	    myChart = echarts.init(chartDom);
	    // 设置图表配置
	    option = {
	      tooltip: { trigger: 'item' },
	      legend: { top: '5%', left: 'center' },
	      series: [
	        {
	          name: 'Access From',
	          type: 'pie',
	          radius: ['40%', '70%'],
	          avoidLabelOverlap: false,
	          label: { show: false, position: 'center' },
	          emphasis: {
	            label: { show: true, fontSize: 20, fontWeight: 'bold' }
	          },
	          labelLine: { show: false },
	          data: [
	            { value: userFinishedList.value.length, name: '完成数量',itemStyle:{color: '#faad14'} },
	            { value: dataList.value.length - userFinishedList.value.length, name: '未完成数量' },
	            
	          ]
	        }
	      ]
	    };
	    // 应用配置
	    if (option && myChart) {
	      myChart.setOption(option);
	    }
	  };
watchEffect(() => {
    loadData();
});
onMounted(async () => {
	await nextTick(); 
    loadData();

	 
});
const doSubmit = () => {
    loadData();
};

const columns = [
    {
      title: "判题状态",
      dataIndex: "status",
      slotName: "status",
      sortable: {
      	sortDirections: [ 'descend']
      }
    },
    {
        title: "题目名称",
        dataIndex: "title",
		sortable: {
			sortDirections: ['ascend', 'descend']
		}
    },
    {
        title: "标签",
        slotName: "tags",
		sortable: {
			sortDirections: ['ascend', 'descend']
		}
    },
    {
        title: "通过率",
        slotName: "acceptedRate",
		sortable: {
			sortDirections: ['ascend', 'descend']
		}
    },
    {
        slotName: "optional",
    },
];


onUnmounted(() => {
  if (myChart) {
    myChart.dispose(); // 释放 DOM 引用
  }
});
</script>

<style scoped>
#manageQuestionView {
}

#homePage {
	display: flex;
	width: 100%;
	justify-content: center;
	align-items: flex-start;
	margin-left: -20px;
	margin-right: -20px;
	padding-left: 20px;
	padding-right: 20px;
}

.left-section {
	flex: 1;
	max-width: 60%;
	display: flex;
	justify-content: center;
}

.filter-space {
	width: 100%;
}

.filter-card {
	padding: 0 !important;
	margin-left: -18px !important;
	margin-right: 0 !important;
	margin-top: 0 !important;
	margin-bottom: 0 !important;
}

.right-section {
	flex-shrink: 0;
	margin-left: 20px;
}
</style>
